package cn.itcast.server.handler;

import cn.itcast.message.RpcResponseMessage;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.concurrent.Promise;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@ChannelHandler.Sharable
public class RpcMessageResponseHandler extends SimpleChannelInboundHandler<RpcResponseMessage> {

    // 用来接收响应结果key=seqId,value=result
    public static final Map<Integer, Promise<Object>> PROMISES = new ConcurrentHashMap<>();

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, RpcResponseMessage msg) throws Exception {
        log.debug("resp: {}", msg);
        // 根据seqId获取对应的promise容器,并且将它从集合中移除（因为使用完就没啥用了，直接丢弃）
        Promise<Object> promise = PROMISES.remove(msg.getSequenceId());
        // 根据响应结果判断，没出异常将结果填进promise容器正常返回，出异常把异常信息填进promise容器并返回
        if (msg.getExceptionValue() == null) {
            promise.setSuccess(msg.getReturnValue());
        } else {
            promise.setFailure(msg.getExceptionValue());
        }
    }
}
